package admin

import (
	"errors"
	"moft/database"
	"moft/model"

	"github.com/quixote-liu/config"
	"gorm.io/gorm"
)

const sysAdminID = "7cd91409-0884-44a1-8931-02371cc3941a845b606e-c072-4bfe-909e-7787f9ffafb3"

func sysAdminUser() model.User {
	return model.User{
		ID:       sysAdminID,
		UserName: config.CONF().GetString("admin", "user_name"),
		Password: config.CONF().GetString("admin", "password"),
		Email:    config.CONF().GetString("admin", "email"),
	}
}

func Init() error {
	adminUser := sysAdminUser()
	db := database.DB()

	var err error

	// checkout admin exist.
	var exist bool = true
	_, err = model.FindUser(db, adminUser.ID)
	if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
		exist = false
	} else if err != nil {
		return err
	}
	if exist {
		return nil
	}

	var role *model.Role
	var adminRoleName = model.AdminRoleName

	// init admin role.
	role, err = model.FindRoleByName(db, adminRoleName)
	if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
		role, err = model.CreateRole(db, &model.Role{RoleName: adminRoleName})
		if err != nil {
			return err
		}
	} else if err != nil {
		return err
	}

	adminUser.RoleID = role.ID
	adminUser.RoleName = role.RoleName
	return model.CreateUser(db, &adminUser)
}

func AssertByNamePass(username, password string) bool {
	u := sysAdminUser()
	return u.UserName == username && u.Password == password
}

func AssertByName(username string) bool {
	u := sysAdminUser()
	return u.UserName == username
}

func AssertByID(id string) bool {
	u := sysAdminUser()
	return u.ID == id
}
